<template>
  <div class="playList">
    <div class="playBox">
      <audio ref="audio"
        :src="audioSrc"
        @timeupdate="onTimeUpdate"
        @canplay="getDuration()"
        preload="metadata"></audio>

      <div class="playLeft">
        <div class="play-bofang">
          <span @click="autoPlayPrevious">
            <img class="auto-img"
              src="../../assets/image/icon/48shangyishou.png" /></span>
          <span class="playbtn"
            @click="clickPlay">
            <img class="auto-img"
              :src="
                this.$store.state.musicState.isClickPlay
                  ? require('../../assets/image/icon/bofang.png')
                  : require('../../assets/image/icon/pause.png')
              "
              alt="" />
          </span>
          <span @click="autoPlayNext">
            <img class="auto-img"
              src="../../assets/image/icon/49xiayishou.png"
              alt="" />
          </span>
        </div>
      </div>
      <div class="playprogrebox">
        <div class="progress">
          <div class="block">
            <span class="demonstration clearfix">
              <div class="musicName fl">
                {{
                  oneMusicPlayData[0] == undefined
                    ? ""
                    : oneMusicPlayData[0].name
                }}
              </div>
              <div class="leadsing fl">
                {{
                  oneMusicPlayData[0] == undefined
                    ? ""
                    : oneMusicPlayData[0].ar[0].name
                }}
              </div>
              <div class="music-time fr">
                <span>{{ currentTime | playTime }} /</span>
                <span> {{ tagetTime | playTime }}</span>
              </div>
            </span>
            <div ref="gressBo">
              <div class="gressBox">
                <div class="gressCon"
                  ref="proGress"></div>
                <div class="gressCircle"
                  ref="gressCircle"></div>
                <div class="gressTras"
                  @click="changeProgress"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="playIcon">
        <!-- 音量 -->
        <div class="volume-box fl">
          <div class="volume">
            <img class="auto-img"
              src="../../assets/image/icon/yinliang.png"
              alt="" />
            <div class="block volumeGress">
              <el-slider v-model="volumeValue"
                vertical
                height="100px"
                @input="volumeGress">
              </el-slider>
            </div>
          </div>
        </div>
        <div class="volume-box fl">
          <div class="volume">
            <img class="auto-img"
              src="../../assets/image/icon/bofangliebiao.png"
              alt="" />
            <div class="volumeGress">
              <!-- 播放顺序 -->
              <div class="category"
                v-for="(item, index) in playOrder"
                :key="index">
                <img class="auto-img"
                  :src="item.src"
                  alt="" />
              </div>
            </div>
          </div>
        </div>
        <div class="volume-box fl"
          @click="downloadMusic">
          <div class="volume">
            <DownLoad ref="mychild" />
            <el-tooltip content="下载"
              placement="top">
              <img class="auto-img"
                src="../../assets/image/icon/xiazai.png"
                alt="" />
            </el-tooltip>
          </div>
        </div>
        <div class="volume-box fl">
          <div class="volume">
            <el-tooltip content="加入收藏"
              placement="top">
              <img class="auto-img"
                src="../../assets/image/icon/jiahao.png"
                alt="" />
            </el-tooltip>
          </div>
        </div>
        <div class="volume-box fl"
          @click="isMusicPList">
          <div class="volume">
            <MusicPlayList v-if="isMusicPlayList"
              class="MusicPlayList" />
            <el-tooltip content="播放列表"
              placement="top">
              <img class="auto-img"
                src="../../assets/image/icon/bofangliebiao.png"
                alt="" />
            </el-tooltip>
          </div>
        </div>
        <div class="Home_icon el-icon-s-home"
          @click="goHome"></div>
      </div>
    </div>
  </div>
</template>

<script>
import MusicPlayList from "./MusicPlayList.vue"
import DownLoad from "@/components/publicCompontents/DownLoad"
import {
  getMusicDetailInfo,
  getURLInfo,
  getMusicLyricInfo,
} from "@/Api/seachApi.js"

export default {
  name: "PlayList",
  components: {
    MusicPlayList,
    DownLoad,
  },

  data() {
    return {
      //播放顺序
      playOrder: [
        { src: require("../../assets/image/icon/suijibofang.png") },
        { src: require("../../assets/image/icon/danquxunhuan.png") },
      ],

      // 播放进度条值
      progressValue: 0,
      // 音量控制
      volumeValue: 20,

      // 下载的歌曲名字
      musicDownLoadName: "",

      // 显示播放列表页面
      isMuPlList: false,

      // // 总时间
      durationTime: 0,
    }
  },

  computed: {
    //   单首歌曲列表详情
    oneMusicPlayData() {
      return this.$store.state.musicState.oneMusicPlayData
    },
    // 获取audio标签
    getAudioElement() {
      return this.$store.state.musicState.audioElement
    },

    // 获取audio路径
    audioSrc() {
      return this.$store.state.musicState.audioSrc
    },
    currentTime() {
      return this.$store.state.musicState.currentTime
    },
    tagetTime() {
      return this.$store.state.musicState.tagetTime
    },
    musicID() {
      return this.$store.state.musicState.musicID
    },
    isMusicPlayList() {
      return this.$store.state.musicState.isMusicPlayList
    },
    // 播放列表数据
    musicPlayListData() {
      return this.$store.state.musicState.musicPlayListData
    },
  },
  async created() {
    await this.$nextTick(() => {
      // 获取audio 标签
      this.$store.commit("musicState/initAudio", this.$refs.audio)

      this.setbackGroundImg(this.oneMusicPlayData[0])
    })
  },
  mounted() {},
  methods: {
    getDuration() {
      // canplay时获取音频总时长
      // console.log("canplay时获取音频总时长", this.getAudioElement);
      this.durationTime = this.getAudioElement.duration
      this.$store.commit("musicState/getTagetTime", this.durationTime)
    },

    // 监听audio播放
    onTimeUpdate(e) {
      // console.log("asdada",e);
      // // 获取播放进度条标签
      let progress = this.$refs.proGress
      // //获取音频当前播放时间
      let currentTime = this.$refs.audio.currentTime
      // console.log(this.$refs.audio.currentTime);
      //获取音频播放总时间 duration
      //let tagetTime = this.getAudioElement.duration;
      // console.log(tagetTime)
      // console.log(currentTime);
      this.$store.commit("musicState/getCurrentTime", currentTime)
      // this.getCurrentTime(currentTime);
      // if (tagetTime + 1 > 1) {
      //   this.$store.commit("musicState/getTagetTime", tagetTime);
      // }
      // 获取的歌词
      this.getMusicLyric()
      // 获取点击的歌曲详情
      this.getOneMusicDetail()
      // 播放进度条
      this.progressValue = parseFloat(
        currentTime *
          (progress.parentElement.offsetWidth / this.durationTime).toFixed(2),
      )
      progress.style.width = this.progressValue + "px"
      this.$refs.gressCircle.style.left =
        (
          this.progressValue -
          this.$refs.gressCircle.style.width / 2 -
          10
        ).toFixed(2) + "px"

      if (this.$refs.audio.ended) {
        this.$store.commit("musicState/isClickPlay", false)
        setTimeout(() => {
          progress.style.width = 0
          this.$refs.gressCircle.style.left = 0
          this.autoPlayNext()
        }, 300)
      }
    },
    // 播放上一首
    autoPlayPrevious() {
      let index = this.musicPlayListData.indexOf(this.musicID)
      index = index - 1 <= 0 ? this.musicPlayListData.length - 1 : index - 1
      this.getURL(this.musicPlayListData[index])
    },
    // 自动播放下一首
    autoPlayNext() {
      let index = this.musicPlayListData.indexOf(this.musicID)
      this.getURL(this.musicPlayListData[index + 1])
    },

    getURL(id) {
      // console.log(id);
      this.$store.commit("musicState/isClickPlay", false)
      const loading = this.$loading({
        background: "rgba(0,0,0,0.6)",
        text: "正在加载中...",
        spinner: "el-icon-loading",
      })
      getURLInfo({ id: id })
        .then((res) => {
          // console.log(res);
          // console.log(1)
          if (res.code == 200) {
            loading.close()
            this.$store.commit("musicState/audioSrc", res.data[0].url)
            this.$store.commit("musicState/SetMusicID", id)
            setTimeout(() => {
              this.$store.commit("musicState/isClickPlay", true)
              this.getAudioElement.play()
            }, 800)
          }
        })
        .catch((err) => {
          loading.close()
          console.log(err)
        })
    },

    // 改变进度条
    changeProgress(e) {
      // 获取播放进度条标签
      // console.log(e)
      let gressBo = this.$refs.gressBo //父-父元素

      if (e.target.className == "gressTras") {
        let current =
          (e.pageX - gressBo.offsetLeft + 2) /
          (gressBo.offsetWidth / this.getAudioElement.duration).toFixed(2)
        this.$refs.audio.currentTime = current
        // console.log(this.$refs.audio.currentTime)
      }
    },

    // 音量改变
    volumeGress() {
      this.$refs.audio.volume =
        this.volumeValue / 100 > 0 ? this.volumeValue / 100 : 20
    },
    // 点击播放或暂停
    clickPlay() {
      // console.log(this.$store.state.musicState.musicPlayListData)
      // console.log("jasdhaihkjhkj", this.audioSrc);
      // console.log("getAudioElement", this.getAudioElement)
      if (!this.getAudioElement) {
        return
      }
      this.$nextTick(() => {
        if (this.getAudioElement.readyState == 4) {
          this.$store.state.musicState.isClickPlay =
            !this.$store.state.musicState.isClickPlay
          if (this.$store.state.musicState.isClickPlay) {
            this.$store.commit("musicState/isClickPlay", true)
            this.$store.commit("musicState/musicPlayListData", this.musicID)
            setTimeout(() => {
              this.getAudioElement.play()
            }, 300)
          } else {
            this.$store.commit("musicState/isClickPlay", false)
            this.getAudioElement.pause()

            // setTimeout(() => {
            //   this.getAudioElement.play();
            // }, 1000);
          }
        } else {
          this.$store.commit("musicState/isClickPlay", false)
          this.getAudioElement.pause()
        }
      })

      // console.log(this.$store.state.musicState.isClickPlay)
      // this.$nextTick(() => {
      // this.$store.state.musicState.isClickPlay = !this.$store.state.musicState.isClickPlay;
      // if (this.$store.state.musicState.isClickPlay) {
      //   console.log("播放状态",this.getAudioElement.readyState);
      //   if (this.getAudioElement.readyState == 4) {
      //     setTimeout(() => {
      //       this.getAudioElement.play();
      //       this.$store.commit("musicState/musicPlayListData", this.musicID);
      //       this.$store.commit(
      //         "musicState/isClickPlay",
      //         this.$store.state.musicState.isClickPlay
      //       );
      //     }, 300);
      //   } else {
      //     this.getAudioElement.pause();
      //     this.$store.commit(
      //       "musicState/isClickPlay",
      //       this.$store.state.musicState.isClickPlay
      //     );
      //     // setTimeout(() => {
      //     //   this.getAudioElement.play();
      //     // }, 1000);
      //   }
      // } else {
      //   this.getAudioElement.pause();
      // }
      // });
    },
    // 获取点击的歌曲详情
    getOneMusicDetail() {
      // console.log("监听成功");
      getMusicDetailInfo(this.musicID)
        .then((res) => {
          // console.log("歌曲详情",res)
          this.musicDownLoadName = res.songs[0].name
          this.$store.commit("musicState/OneMusicPlayData", res.songs)
          // 加入播放列表
          // this.$store.commit("musicPlayListData", this.musicID);
          // console.log(this.$store.state.musicState.oneMusicPlayData)
        })
        .catch((err) => {
          // console.log(err);
        })
    },

    // 获取的歌词
    getMusicLyric() {
      getMusicLyricInfo({ id: this.musicID })
        .then((res) => {
          // console.log('获取的歌词',res);
          this.$store.commit("musicState/lyricData", res.lrc.lyric)
          // this.$store.dispatch("lyricData", res.data.lrc.lyric);
        })
        .catch((err) => {
          // console.log(err);
        })
    },
    // 设置背景图片
    setbackGroundImg(data) {
      // console.log(data)
      if (data != undefined) {
        // console.log(data.al.picUrl)
        //  let bgcImg = `position:fixed;width:100%;height:100%;filter:blur(50px);background-image:url(${data.al.picUrl});z-index:-1;`
        this.$store.commit("musicState/bgcImg", data.al.picUrl)
      }
    },

    // 显示播放列表页面
    isMusicPList() {
      this.isMuPlList = !this.isMuPlList
      this.$store.commit("musicState/isMusicPlayList", this.isMuPlList)
    },

    // 下载音乐
    downloadMusic() {
      if (this.audioSrc) {
        this.$nextTick(() => {
          //  因为数据只有一条，则无需[0]
          this.$refs.mychild.downLoad(this.musicID, this.musicDownLoadName)
        })
      }
    },
    // 返回首頁
    goHome() {
       this.$router.push({ name: 'Home' })
    },

    // 修改audio元素，保存在公共数据 state
    // getAudioChange(audio) {
    //   this.$store.commit("musicState/initAudio", audio);
    // },
    // getCurrentTime(currentTime) {
    //   this.$store.commit("musicState/getCurrentTime", currentTime);
    // },
    // getTagetTime(time) {
    //   this.$store.commit("musicState/getTagetTime", time);
    // },
  },
}
</script>

<style lang="scss" scoped>
@import "@/styles/public.scss";
.playList {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  // height: 100%;
  height: 100px;

  .playBox {
    height: 100%;
    display: flex;

    // background-color: rgba(0,0,0,0);
    .playLeft {
      height: 100%;
      // background-color: purple;

      flex: 2;
      .play-bofang {
        display: inline-block;
        height: 100%;
        min-width: 260px;

        span {
          display: inline-block;
          margin-left: 30px;
          margin-top: 20px;
          width: 48px;
          height: 48px;
          cursor: pointer;
        }
        .playbtn {
          width: 52px;
          height: 52px;
        }
      }
    }
    .playprogrebox {
      // text-align: center;
      width: 900px;
      // min-width: 900px;
      // flex: 6;
      font-size: 20px;
      font-weight: bold;
      color: #fff;
      padding: 0 10px;
    }
    .progress {
      width: 100%;
      height: 100%;
      // background-color: rgba(0,0,0,.1);
      // background-color: green;
      .musicName {
        margin-right: 26px;
      }

      .gressBox {
        width: 100%;
        height: 10px;
        margin-top: 15px;
        border-radius: 5px;
        background-color: #fff;
        position: relative;
      }
      .gressTras {
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0);
        position: absolute;
        top: 0;
        left: 0;
        border-radius: 5px;
        z-index: 20;
        cursor: pointer;
      }
      .gressCon {
        width: 0px;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        border-radius: 5px;
        background-color: blue;
        z-index: 10;
      }
      .gressCircle {
        width: 24px;
        height: 24px;
        background-color: skyblue;
        border-radius: 50%;
        position: absolute;
        top: calc(100% - 17px);
        left: -10px;
        z-index: 12;
      }
      // 进度条
      ::v-deep .el-slider__runway {
        height: 8px;
        .el-slider__bar {
          height: 8px;
        }
      }
    }
    //图标盒子
    .playIcon {
      min-width: 520px;
      height: 100%;
      position: relative;
      // background-color: blue;
      flex: 4;
      .volume-box {
        height: 100%;
        width: 50px;
        margin: 0 10px;
        // background-color: red;

        position: relative;
      }
      .loopFor {
        flex: 1;
      }
      .Home_icon {
        position: absolute;
        right: 20px;
        top: calc(50% - 23px);
        font-size: 46px;
        cursor: pointer;
        color: #fff;

        &:hover {
          color: #3e3e3e;
        }
      }
    }
    .MusicPlayList {
      position: absolute;
      top: -720px;
      left: -460px;
    }

    .volume {
      width: 30px;
      height: 30px;
      padding: 10px;
      margin-top: 20px;
      cursor: pointer;
      // margin-left: 10px;
      .volumeGress {
        display: none;
        padding: 10px 5px;
        border: 1px solid #ccc;
        // background-color: #ccc;
        position: absolute;
        bottom: 70px;
        left: calc(100% - 50px);

        .category {
          width: 30px;
          height: 30px;
          padding: 4px;
          margin-bottom: 10px;
          &:hover {
            // background-color: rgba(0, 0, 0, 0.5);
          }
        }
      }
      &:hover {
        .volumeGress {
          display: block;
        }
      }
    }
  }
}
</style>
